package Synchronized_1;

class BankAccount {
    private int balance = 1000;
    public synchronized void deposit(int amount) {
        int temp = balance + amount;
        try {
            Thread.sleep(10); // 模拟处理延迟
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        balance = temp;
        System.out.println(Thread.currentThread().getName() + " 存入 " + amount + ", 余额: " + balance);
    }
    public synchronized void withdraw(int amount) {
        if (balance >= amount) {
            int temp = balance - amount;
            try {
                Thread.sleep(10); // 模拟处理延迟
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            balance = temp;
            System.out.println(Thread.currentThread().getName() + " 取出 " + amount + ", 余额: " + balance);
        } else {
            System.out.println(Thread.currentThread().getName() + " 余额不足");
        }
    }
}

public class 同步方法{
    public static void main(String[] args) {
        final BankAccount account = new BankAccount();

        // 创建10个存款线程
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                public void run() {
                    account.deposit(100);
                }
            }, "存款线程-" + i).start();
        }

        // 创建10个取款线程
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                public void run() {
                    account.withdraw(100);
                }
            }, "取款线程-" + i).start();
        }
    }
}